<?php
/**
 * @package		简易CMS
 * @subpackage	插件函数包
 * @version		$Id: option_portal.php 29 2013-05-07 06:45:56Z hopingsoft@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if (! defined ( 'IN_JYCMS' )) {
	exit ( 'Access Denied' );
}

define ( 'CURSCRIPT', 'portal' );
class portal_ctrl extends application {
	var $allowaction = array (
			'list',
			'view',
			'attachment',
			'index'
	);
	function __construct() {
		$this->portal_ctrl ();
	}
	function portal_ctrl() {
		global $_G;
		$_G ['gp_option'] = 'portal';
		$this->cachelist = array (
				'portalcategory',
				'customfields'
		);
		parent::__construct ();
	}
	function onAttachment() {
		global $_G;
		$operation = $_G ['gp_op'] ? $_G ['gp_op'] : '';

		$id = empty ( $_GET ['id'] ) ? 0 : intval ( $_GET ['id'] );
		$aid = empty ( $_GET ['aid'] ) ? '' : intval ( $_GET ['aid'] );
		$attach = DB::fetch_first ( "SELECT * FROM #__common_attachment WHERE attachid='$id'" );
		if (empty ( $attach )) {
			showmessage ( "Download the file specified does not exist!" );
		}

		if ($operation == 'delete') {
			if (! $_G ['group'] ['allowmanagearticle'] && $_G ['uid'] != $attach ['uid']) {
				showmessage ( "You do not have permission to delete the file" );
			}
			if ($aid) {
				DB::query ( "UPDATE #__portal_article_title SET pic = '' WHERE aid='$aid'", 'UNBUFFERED' );
			}
			DB::query ( "DELETE FROM #__common_attachment WHERE attachid='$id'" );
			pic_delete ( $attach ['attachment'], 'portal', $attach ['thumb'], $attach ['remote'] );
			showmessage ( "Photo deleted!" );
		} else {
			$filename = $_G ['setting'] ['attachdir'] . '/portal/' . $attach ['attachment'];
			if (! $attach ['remote'] && ! is_readable ( $filename )) {
				showmessage ( 'Attachment file does not exist or could not read, please contact your administrator.' );
			}

			$readmod = 2; // read local file's function: 1=fread 2=readfile
			              // 3=fpassthru 4=fpassthru+multiple
			$range = 0;
			if ($readmod == 4 && ! empty ( $_SERVER ['HTTP_RANGE'] )) {
				list ( $range ) = explode ( '-', (str_replace ( 'bytes=', '', $_SERVER ['HTTP_RANGE'] )) );
			}

			if ($attach ['remote'] && ! $_G ['setting'] ['ftp'] ['hideurl'] && $attach ['isimage']) {
				dheader ( 'location:' . $_G ['setting'] ['ftp'] ['attachurl'] . 'portal/' . $attach ['attachment'] );
			}

			$filesize = $attach ['filesize'];
			$attach ['filename'] = '"' . (strtolower ( CHARSET ) == 'utf-8' && strexists ( $_SERVER ['HTTP_USER_AGENT'], 'MSIE' ) ? urlencode ( $attach ['filename'] ) : $attach ['filename']) . '"';

			dheader ( 'Date: ' . gmdate ( 'D, d M Y H:i:s', $attach ['dateline'] ) . ' GMT' );
			dheader ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s', $attach ['dateline'] ) . ' GMT' );
			dheader ( 'Content-Encoding: none' );
			dheader ( 'Content-Disposition: attachment; filename=' . $attach ['filename'] );
			dheader ( 'Content-Type: ' . $attach ['filetype'] );
			dheader ( 'Content-Length: ' . $filesize );

			if ($readmod == 4) {
				dheader ( 'Accept-Ranges: bytes' );
				if (! empty ( $_SERVER ['HTTP_RANGE'] )) {
					$rangesize = ($filesize - $range) > 0 ? ($filesize - $range) : 0;
					dheader ( 'Content-Length: ' . $rangesize );
					dheader ( 'HTTP/1.1 206 Partial Content' );
					dheader ( 'Content-Range: bytes=' . $range . '-' . ($filesize - 1) . '/' . ($filesize) );
				}
			}

			$attach ['remote'] ? getremotefile ( $attach ['attachment'] ) : getlocalfile ( $filename, $readmod, $range );
		}
	}

	/**
	 * 文章首页（默认的站点首页
	 *
	 * @global array $_G 系统全局变量
	 */
	function onIndex() {
		global $_G, $mainframe;
		define ( 'CURMODULE', 'portal' );
		$navtitle = $_G ['setting'] ['navs'] [1] ['navname'];

		$metakeywords = $_G ['setting'] ['seokeywords'] ['portal'];
		if (! $metakeywords) {
			$metakeywords = $_G ['setting'] ['navs'] [1] ['navname'];
		}

		$metadescription = $_G ['setting'] ['seodescription'] ['portal'];
		if (! $metadescription) {
			$metadescription = $_G ['setting'] ['navs'] [1] ['navname'];
		}

		include_once template ( 'diy:portal/index' );
	}

	/**
	 * 浏览文章
	 *
	 * @global array $_G 系统全局变量
	 */
	function onView() {
		global $_G;
		loadcache ( 'customfields' );
		$customfields = $_G ['cache'] ['customfields'];
		$tophtml = $bottomhtml = '';
		define ( 'CURMODULE', 'view' );
		$aid = empty ( $_GET ['aid'] ) ? 0 : intval ( $_GET ['aid'] );
		if (empty ( $aid )) {
			showmessage ( "To view the article did not specify the correct ID!" );
		}
		$article = DB::fetch_first ( "SELECT * FROM #__portal_article_title WHERE aid='$aid'" );
		require_once libfile ( 'function/portalcp' );

		if (empty ( $article ) || ($article ['status'] > 0 && $article ['uid'] != $_G ['uid'] && ! $_G ['group'] ['allowmanagearticle'] && $_G ['adminid'] != 1 && $_G ['gp_modarticlekey'] != modauthkey ( $article ['aid'] ))) {
			showmessage ( "To view the article specified does not exist or are being reviewed!" );
		}
		DB::query ( "SELECT a.*, b.tagname FROM #__common_tags a LEFT JOIN #__common_tagslist b on b.tagid=a.tagid WHERE a.itemid='$aid' AND a.tagtype='portal'" );
		$tags = DB::fetch_all ();
		$article ['tags'] = $tags;

		DB::query ( "UPDATE #__portal_article_title SET viewnum=viewnum+1 WHERE aid='$aid'" );

		if ($article ['url']) {
			dheader ( "location:{$article['url']}" );
			exit ();
		}
		$article ['custom'] = array (
				'name' => '',
				'key' => array (),
				'value' => array ()
		);
		if (! empty ( $article ['customfieldid'] )) {
			$article ['custom'] ['value'] = unserialize ( $article ['customfieldtext'] );
			if ($article ['custom'] ['value']) {
				$fields = $customfields [$article ['customfieldid']];
				$article ['custom'] ['name'] = $fields ['name'];
				$article ['custom'] ['key'] = $fields ['customfieldtext'];
				foreach ( $article ['custom'] ['value'] as $key => $value ) {
					if ($value) {
						$cf = $article ['custom'] ['key'] [$key];
						ProcessCustomField ( $cf, $value, $tophtml, $bottomhtml );
					}
				}
				if ($tophtml)
					$tophtml = '<table class="customfields">' . $tophtml . '</table>';
				if ($bottomhtml)
					$bottomhtml = '<table class="customfields">' . $bottomhtml . '</table>';
			}
		}
		$cat = category_remake ( $article ['catid'] );
		// pre($cat);
		$article ['pic'] = pic_get ( $article ['pic'], 'portal', $article ['thumb'], $article ['remote'] );

		$page = intval ( $_GET ['page'] );
		if ($page < 1)
			$page = 1;
		$start = $page - 1;

		$content = array ();
		$multi = '';

		$query = DB::query ( "SELECT * FROM #__portal_article_content WHERE aid='$aid' ORDER BY pageorder LIMIT $start,1" );
		$content = DB::fetch ( $query );

		$content ['content'] = $tophtml . blog_bbcode ( $content ['content'] ) . $bottomhtml;

		$multi = multi ( $article ['contents'], 1, $page, "index.php?task=view&aid=$aid" );
		$org = array ();
		/**
		 * 读取相关文章，这里来说，如果是自动采集过来的文章，通常是不会手动去设置相关文章的，所以就以KID为主要的判断依据
		 */
		$article ['related'] = array ();
		if ($article ['kid']) {
			$kid = $article ['kid'];
			$query = DB::query ( "SELECT a.aid, a.title
				FROM #__portal_article_title a
				WHERE a.aid!='$aid' AND a.kid='$kid'
				ORDER BY a.aid DESC LIMIT 0,10" );
		} else {
			$query = DB::query ( "SELECT a.aid,a.title
				FROM #__portal_article_related r
				LEFT JOIN #__portal_article_title a ON a.aid=r.raid
				WHERE r.aid='$aid' ORDER BY r.displayorder" );
		}
		while ( $value = DB::fetch ( $query ) ) {
			$article ['related'] [] = $value;
		}
		// 读取评论
		$article ['allowcomment'] = ! empty ( $cat ['allowcomment'] ) && ! empty ( $article ['allowcomment'] ) ? 1 : 0;
		$_G ['curcatid'] = $_G ['catid'] = $_GET ['catid'] = $article ['catid'];
		if ($cat ['upid']) {
			$_G ['topcatid'] = $cat ['upid'];
		} else {
			$_G ['topcatid'] = $_G ['catid'];
		}
		$common_url = '';
		$commentlist = array ();
		if ($article ['allowcomment']) {
			$form_url = "index.php?option=comment&task=manage";
			if ($article ['commentnum'] > 0) {
				$common_url = "index.php?option=comment&task=show&aid=$aid";
				$query = DB::query ( "SELECT * FROM #__common_comment WHERE aid='$aid' ORDER BY cid DESC LIMIT 0,110" );
				while ( $value = DB::fetch ( $query ) ) {
					if ($value ['status'] == 0 || $value ['uid'] == $_G ['uid'] || $_G ['adminid'] == 1) {
						$value ['allowop'] = 1;
						$commentlist [] = $value;
					}
				}
			}
		}

		// 给投票做个HASH值，避免恶意投票
		$hash = md5 ( $article ['uid'] . "\t" . $article ['dateline'] );
		$id = $article ['aid'];
		$idtype = 'aid';
		// 检查一下本文是否采集回来地，且是否需要读取正文内容
		$this->load ( 'function/focus' );
		$article = array_merge ( $article, $content );
		$article = focus_check ( $article );
		$content ['content'] = $article ['content'];

		$content ['content'] = str_replace ( 'http://jycms.com.ru/', $_G ['siteurl'], $content ['content'] );
		$result = $this->plugin->loadPlugins ( 'content' );
		if ($result) {
			$content ['content'] = $this->plugin->trigger ( 'parsecontent', $content ['content'] );
		}

		// $content['content'] = getTranslate($content['content'], 'zh-cn', 'en');

		/**
		 * 读取图片
		 */
		$query = DB::query ( "SELECT * FROM #__common_attachment WHERE aid='$aid' AND isimage='1'" );
		$aimgs = array ();
		while ( $value = DB::fetch ( $query ) ) {
			if ($value ['thumb']) {
				$value ['thumb'] = $value ['attachment'] . '.thumb.jpg';
			} else {
				$value ['thumb'] = $value ['attachment'];
			}
			$value ['thumb'] = $_G ['setting'] ['attachurl'] . 'portal/' . $value ['thumb'];
			$value ['pic'] = $_G ['setting'] ['attachurl'] . 'portal/' . $value ['attachment'];
			$basename = basename ( $value ['pic'] );
			if (! strpos ( $content ['content'], $basename ))
				$aimgs [] = $value;
		}

		loadcache ( 'click' );
		$clicks = empty ( $_G ['cache'] ['click'] ['aid'] ) ? array () : $_G ['cache'] ['click'] ['aid'];
		$maxclicknum = 0;
		foreach ( $clicks as $key => $value ) {
			$value ['clicknum'] = $article ["click{$key}"];
			$value ['classid'] = mt_rand ( 1, 4 );
			if ($value ['clicknum'] > $maxclicknum)
				$maxclicknum = $value ['clicknum'];
			$clicks [$key] = $value;
		}

		$clickuserlist = array ();
		$query = DB::query ( "SELECT * FROM #__common_clickuser
			WHERE id='$id' AND idtype='$idtype'
			ORDER BY dateline DESC
			LIMIT 0,24" );
		require_once libfile ( 'function/misc' );
		while ( $value = DB::fetch ( $query ) ) {
			$value ['clickname'] = $clicks [$value ['clickid']] ['name'];
			if (! $value ['uid']) {
				$value ['username'] = convertip ( $value ['username'] ) . '网友';
			}
			$clickuserlist [] = $value;
		}

		$article ['dateline'] = dgmdate ( $article ['dateline'] );

		$navtitle = $article ['title'] . ($page > 1 ? " ( $page )" : '') . ' - ' . $cat ['catname'];
		$metakeywords = $article ['title'];
		$metakeywords = $article ['keywords'];
		$metadescription = $article ['summary'] ? $article ['summary'] : $article ['title'];
		include_once template ( "diy:portal/view:{$article['catid']}", NULL, NULL, NULL, $cat ['contenttplname'] );
	}

	/**
	 * 分类内容列表
	 *
	 * @global array $_G 系统全局变量
	 */
	function onList() {
		global $_G;
		define ( 'CURMODULE', 'list' );

		$_G ['catid'] = $catid = max ( 0, intval ( $_GET ['catid'] ) );
		if (empty ( $catid )) {
			showmessage ( "Not correct to specify which categories!", dreferer () );
		}
		$portalcategory = &$_G ['cache'] ['portalcategory'];
		$cat = $portalcategory [$catid];

		if (empty ( $cat )) {
			showmessage ( "To specify which category does not exist!", dreferer () );
		}
		require_once libfile ( 'function/portalcp' );
		if ($cat ['closed'] && ! $_G ['group'] ['allowdiy']) {
			showmessage ( "To specify which category has been closed!", dreferer () );
		}

		if (! empty ( $cat ['url'] ))
			dheader ( 'location:' . $cat ['url'] );
		if (defined ( 'SUB_DIR' ) && $_G ['siteurl'] . substr ( SUB_DIR, 1 ) != $cat ['caturl'] || ! defined ( 'SUB_DIR' ) && $_G ['siteurl'] != substr ( $cat ['caturl'], 0, strrpos ( $cat ['caturl'], '/' ) + 1 )) {
			// dheader('location:'.$cat['caturl'], '301');
		}

		$cat = category_remake ( $catid );
		$_G ['mnid'] = 'mn_P' . $cat ['topid'];
		$page = max ( 1, intval ( $_GET ['page'] ) );
		$navtitle = $cat ['catname'] . ($page > 1 ? " ($page)" : '');
		$metadescription = empty ( $cat ['description'] ) ? $cat ['catname'] : $cat ['description'];
		$metakeywords = empty ( $cat ['keyword'] ) ? $cat ['catname'] : $cat ['keyword'];
		$page = max ( 1, intval ( $_GET ['page'] ) );
		$count = DB::result ( DB::query ( "SELECT COUNT(*) FROM #__portal_article_title at WHERE catid='$catid'" ), 0 );
		$multi = multi ( $count, 10, $page, $cat ['caturl'] );

		$file = 'portal/list:' . $catid;
		if ($cat ['upid'])
			$_G ['topcatid'] = $cat ['upid'];
		else
			$_G ['topcatid'] = $catid;
		$_G ['curcatid'] = $catid;
		include template ( 'diy:' . $file, NULL, NULL, NULL, $cat ['primaltplname'] );
	}
}
